package com.ruoyi.system.controller;

import com.github.pagehelper.PageHelper;
import com.ruoyi.common.annotation.RepeatSubmit;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.system.domain.KsLetter;
import com.ruoyi.system.domain.KsOrder;
import com.ruoyi.system.domain.KsReplyLog;
import com.ruoyi.system.domain.OrderLetter;
import com.ruoyi.system.mapper.*;
import com.ruoyi.system.service.IKsLetterService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.annotation.security.PermitAll;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

/**
 * 客诉工单站内信Controller
 *
 * @author hjf
 * @date 2025-07-29
 */
@RestController
@RequestMapping("/hmk/ksLetter")
public class KsLetterController extends BaseController {
    @Autowired
    private IKsLetterService ksLetterService;
    @Autowired
    private KsLetterMapper ksLetterMapper;

    @Autowired
    private OrderLetterMapper orderLetterMapper;

    @Autowired
    private KsOrderMapper ksOrderMapper;

    @Autowired
    private KsReplyLogMapper ksReplyLogMapper;

    @Autowired
    private SysUserMapper sysUserMapper;

    /**
     * 查询客诉工单站内信列表
     */
    @PreAuthorize("@ss.hasPermi('hmk:ksLetter:list')")
    @GetMapping("/list")
    public TableDataInfo list(KsLetter ksLetter) {
        startPage();
        PageHelper.orderBy("is_agree desc");
        List<KsLetter> list = ksLetterService.selectKsLetterList(ksLetter);
        return getDataTable(list);
    }


    @PermitAll
    @PostMapping("/getByAuditUser")
    public AjaxResult getByAuditUser(@RequestBody KsLetter ksLetter) {
        if (null == ksLetter.getAuditUser()) {
            ksLetter.setAuditUser(SecurityUtils.getUserId());
        }
        List<KsLetter> list = ksLetterMapper.selectKsLetterList2(ksLetter);
        if (list.size() > 0) {
            return success(list.get(0));
        } else {
            return success();
        }
    }


    @PermitAll
    @PostMapping("/getKsMessageNumber")
    public AjaxResult getKsMessageNumber(@RequestBody KsLetter ksLetter) {
        if (null == ksLetter.getAuditUser()) {
            ksLetter.setAuditUser(SecurityUtils.getUserId());
        }
        List<KsLetter> list = ksLetterMapper.selectKsLetterList2(ksLetter);
        HashMap<String, Integer> map = new HashMap();
        if (list.size() > 0) {
            map.put("ksMessageNumber", list.size());
            return success(map);
        } else {
            return success();
        }
    }

    @PermitAll
    @PostMapping("/getOrderByAuditUser")
    public AjaxResult getOrderByAuditUser(@RequestBody OrderLetter orderLetter) {
        if (null == orderLetter.getAuditUser()) {
            orderLetter.setAuditUser(SecurityUtils.getUserId());
        }
        List<OrderLetter> list = orderLetterMapper.selectOrderLetterList2(orderLetter);
        if (list.size() > 0) {
            return success(list.get(0));
        } else {
            return success();
        }
    }


    @PermitAll
    @PostMapping("/delayHandler")
    public AjaxResult delayHandler(@RequestBody KsLetter ksLetter) {
        if (null == ksLetter.getAuditUser()) {
            ksLetter.setAuditUser(SecurityUtils.getUserId());
        }
        KsLetter upKs = new KsLetter();
        upKs.setIsAgree(3L);
        upKs.setId(ksLetter.getId());
        ksLetterService.updateKsLetter(upKs);
        return success();
    }


    @PermitAll
    @PostMapping("/delayOrderHandler")
    public AjaxResult delayOrderHandler(@RequestBody OrderLetter orderLetter) {
        if (null == orderLetter.getAuditUser()) {
            orderLetter.setAuditUser(SecurityUtils.getUserId());
        }
        OrderLetter oL = new OrderLetter();
        oL.setIsAgree(3L);
        oL.setId(orderLetter.getId());
        orderLetterMapper.updateOrderLetter(oL);
        return success();
    }

    /**
     * 导出客诉工单站内信列表
     */
    @PreAuthorize("@ss.hasPermi('hmk:ksLetter:export')")
    @PostMapping("/export")
    public void export(HttpServletResponse response, KsLetter ksLetter) {
        List<KsLetter> list = ksLetterService.selectKsLetterList(ksLetter);
        ExcelUtil<KsLetter> util = new ExcelUtil<KsLetter>(KsLetter.class);
        util.exportExcel(response, list, "客诉工单站内信数据");
    }


    /**
     * 获取客诉工单站内信详细信息
     */
    @PreAuthorize("@ss.hasPermi('hmk:ksLetter:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return success(ksLetterService.selectKsLetterById(id));
    }


    /**
     * 新增客诉工单站内信
     */
    @PreAuthorize("@ss.hasPermi('hmk:ksLetter:add')")
    @PostMapping
    public AjaxResult add(@RequestBody KsLetter ksLetter) {
        return toAjax(ksLetterService.insertKsLetter(ksLetter));
    }

    /**
     * 修改客诉工单站内信
     */
    @PreAuthorize("@ss.hasPermi('hmk:ksLetter:edit')")
    @PutMapping
    @RepeatSubmit(interval = 60000)
    public AjaxResult edit(@RequestBody KsLetter ksLetter) {
        ksLetter.setReplyTime(new Date());
        SysUser sysUser = SecurityUtils.getLoginUser().getUser();
        KsLetter oldKsLetter = ksLetterService.selectKsLetterById(ksLetter.getId());
        SysUser issuerUser = sysUserMapper.selectUserById(oldKsLetter.getIssuerUser());
        if (1L == ksLetter.getIsAgree()) {
            KsOrder oldKsOrder = ksOrderMapper.selectKsOrderByKsId(oldKsLetter.getKsId());
            KsReplyLog kRL = new KsReplyLog();
            kRL.setOrderId(oldKsLetter.getOrderId());
            kRL.setKsId(oldKsOrder.getId());
            kRL.setReplyUserId(sysUser.getUserId());
            kRL.setReplyContent("【同意方案】" + sysUser.getNickName() + "同意了" + issuerUser.getNickName() + "的处理方案(" + oldKsLetter.getIssuerContent() + ")意见:同意," + ksLetter.getReplyContent());
            kRL.setCreateTime(new Date());
            ksReplyLogMapper.insertKsReplyLog(kRL);

            KsOrder ksOrder = new KsOrder();
            ksOrder.setKsId(oldKsLetter.getKsId());
            ksOrder.setState(4);
            ksOrderMapper.updateKsOrderByKsId(ksOrder);
        } else if (2L == ksLetter.getIsAgree()) {
            KsOrder oldKsOrder = ksOrderMapper.selectKsOrderByKsId(oldKsLetter.getKsId());
            KsReplyLog kRL = new KsReplyLog();
            kRL.setOrderId(oldKsLetter.getOrderId());
            kRL.setKsId(oldKsOrder.getId());
            kRL.setReplyUserId(sysUser.getUserId());
            kRL.setReplyContent("【不同意方案】" + sysUser.getNickName() + "不同意" + issuerUser.getNickName() + "的处理方案(" + oldKsLetter.getIssuerContent() + ")意见:不同意," + ksLetter.getReplyContent());
            kRL.setCreateTime(new Date());
            ksReplyLogMapper.insertKsReplyLog(kRL);
            KsOrder ksOrder = new KsOrder();
            ksOrder.setKsId(oldKsLetter.getKsId());
            ksOrder.setState(2);
            ksOrderMapper.updateKsOrderByKsId(ksOrder);
        }

        return toAjax(ksLetterService.updateKsLetter(ksLetter));
    }

    /**
     * 删除客诉工单站内信
     */
    @PreAuthorize("@ss.hasPermi('hmk:ksLetter:remove')")
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(ksLetterService.deleteKsLetterByIds(ids));
    }
}
